<template>
    <div>
        <el-upload class="upload-audio" :action="action" :headers="headers" :on-success="handleSuccess" :before-upload="beforeUpload"
                   :show-file-list="false" :accept="accept" style="width: 100%;">
            <!--<img v-if="editForm.picture != ''" :src="editForm.picture" class="avatar">-->
            <i v-if="!value" class="el-icon-plus upload-audio-icon"/>
            <div v-else style="display: flex;align-items: center;">
                <i class="el-icon-delete remove" @click.stop="clearValue" style="font-size: 2em;margin-right: 10px;"/>
                <audio :src="value" controls style="display: block; flex-grow: 1"/>
            </div>
        </el-upload>
    </div>
</template>

<script>
    import {getToken} from '@/utils/auth'

    export default {
        name: "UploadAudio",
        props: {
            value: String,
            action: {
                type: String,
                default: process.env.VUE_APP_BASE_API + '/admin/component/oss/upload'
            },
            accept: {
                type: String,
                default: 'audio/*'
            },
        },
        data() {
            return {
                headers: {
                    token: ''
                },
            }
        },
        model: {
            prop: 'value',
            event: 'change'
        },
        methods: {
            beforeUpload(file) {
                console.log(arguments)
                //声音格式要考虑h5的播放能力
                let isType = /^audio\/(mp3|mpeg|wav|pcm|ogg)$/i.test(file.type);
                let isSize = file.size / 1024 / 1024 < 8;

                if (!isType) {
                    this.$message.error('不支持的声音格式!');
                }
                if (!isSize) {
                    this.$message.error('上传文件大小不能超过 8MB!');
                }
                this.headers.token = getToken();
                return isType && isSize;
            },
            handleSuccess(res, file) {
                console.log(arguments)
                this.value = res.data.urls;
                this.$emit('change', res.data.urls)
            },
            clearValue() {
                this.value = '';
                this.$emit('change', '');
            }
        }
    }
</script>

<style>
    .upload-audio .el-upload {
        display: block;
        text-align: left;
    }

    .upload-audio-icon {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        font-size: 28px;
        color: #8c939d;
        width: 70px;
        height: 70px;
        line-height: 70px;
        text-align: center;
    }
</style>
